package com.marchsoft.group.manager.security.service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.marchsoft.group.manager.common.enums.ResultEnum;
import com.marchsoft.group.manager.common.exception.BadRequestException;
import com.marchsoft.group.manager.security.entity.SecurityUserDetails;
import com.marchsoft.group.manager.system.entity.User;
import com.marchsoft.group.manager.system.mapper.RoleMapper;
import com.marchsoft.group.manager.system.mapper.UserMapper;
import com.marchsoft.group.manager.system.service.IRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service("jwtUserDetailsService")
public class JwtUserDetailsService implements UserDetailsService {
  @Autowired
    private UserMapper userMapper;

  @Autowired
  private IRoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .select("username","password")
                .eq("username",username);
        User user = userMapper.selectOne(queryWrapper);
        if(user==null){
           throw  new BadRequestException(ResultEnum.LOGIN_INFO_NOT_FOUND);
        }
        log.info("当前登录者的信息"+user);
        //获取用户的信息
         Long userName =user.getUsername();
        String password = new BCryptPasswordEncoder().encode(user.getPassword());
        //获取用户权限
        String authority =  roleService.getAuthority(userName);
        //设置用户权限
        List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
        //返回当前接口的实现类
        return new SecurityUserDetails(userName.toString(),password,authorities);


    }
}
